package com.minghe


import com.xue.StockProto
import com.xue.StockServiceGrpc
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.grpc.stub.StreamObserver
import io.quarkus.grpc.GrpcService
import jakarta.inject.Inject
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.format.DateTimeParseException

//@GrpcService
//class StockServiceImpl : StockServiceGrpc.StockServiceImplBase(){
//
//    @Inject
//    lateinit var stockRepository : Init_StockRepository
//
//    override fun getStock(
//        request: StockProto.StockRequest?,
//        responseObserver: StreamObserver<StockProto.StockResponse>?
//    ) {
//        println("stock server start")
//        if (request == null) {
//            return
//        }
//
//        var response = StockProto.StockResponse.newBuilder()
//        val result = stockRepository.findSummary(request.storeCode, request.productCode, Instant.parse(request.stockTime))
//
//        if (result != null) {
//            response.setStoreCode(result.storeCode)
//            response.setProductCode(result.productCode)
//            response.setStockTime(result.stockDate.toString())
//            response.setStockNum(result.quantity.toInt())
//        }
//
//        responseObserver?.onNext(response.build())
//        responseObserver?.onCompleted()
//
//    }
//}


@GrpcService
class StockServiceImpl : StockServiceGrpc.StockServiceImplBase() {

    @Inject
    lateinit var stockRepository: Init_StockRepository

    override fun getStock(
        request: StockProto.StockRequest?,
        responseObserver: StreamObserver<StockProto.StockResponse>?
    ) {
        GlobalScope.launch {

            println("222")
            try {
                if (request == null) {
                    throw Status.INVALID_ARGUMENT.withDescription("Request is null").asRuntimeException()
                }

                println("33333")
                // 1. 解析日期
                val stockDate = try {
                    Instant.parse(request.stockTime)
                } catch (e: DateTimeParseException) {
                    throw Status.INVALID_ARGUMENT
                        .withDescription("Invalid stockTime format (expected ISO-8601)")
                        .asRuntimeException()
                }
                // 2. 查询数据库
                val result = stockRepository.findSummary(request.storeCode, request.productCode, stockDate)
                    ?: throw Status.NOT_FOUND
                        .withDescription("No stock record found for parameters")
                        .asRuntimeException()

                // 3. 转换 BigDecimal 到 Int（需处理溢出）
                val stockNum = try {
                    result.quantity.toInt()
                } catch (e: ArithmeticException) {
                    throw Status.OUT_OF_RANGE
                        .withDescription("Stock quantity exceeds integer limit")
                        .asRuntimeException()
                }

                // 4. 构建响应
                val response = StockProto.StockResponse.newBuilder()
                    .setStoreCode(result.storeCode)
                    .setProductCode(result.productCode)
                    .setStockTime(result.stockDate.toString())
                    .setStockNum(stockNum)
                    .build()

                responseObserver?.onNext(response)
                responseObserver?.onCompleted()

            } catch (e: StatusRuntimeException) {
                responseObserver?.onError(e)
            } catch (e: Exception) {
                // 捕获所有未处理的异常
                responseObserver?.onError(
                    Status.INTERNAL
                        .withDescription("Internal error: ${e.message}")
                        .asRuntimeException()
                )
            }
        }
    }
}